package com.hirsi.common.core.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import com.hirsi.common.core.constant.HeaderConstant;

import javax.servlet.http.HttpServletRequest;

public class AccessTokenUtil {

    public static String getAccessToken() {
        HttpServletRequest request = HttpContextUtil.getRequest();
        if (request == null) return null;
        return request.getHeader(HeaderConstant.ACCESS_TOKEN);
    }

    private static JSONObject getJwtPayloads() {
        String accessToken = getAccessToken();
        if (StrUtil.isBlank(accessToken)) return null;
        try {
            JWT jwt = JWT.of(accessToken);
            JSONObject payloads = jwt.getPayloads();
            return payloads;
        } catch (JWTException e) {
            return null;
        }
    }

    public static Integer getUserId() {
        JSONObject payloads = getJwtPayloads();
        if (payloads == null) return null;
        return payloads.getInt("id");
    }

    public static String getPhone() {
        JSONObject payloads = getJwtPayloads();
        if (payloads == null) return null;
        return payloads.getStr("phone");
    }

    public static String getDeveloperCode() {
        JSONObject payloads = getJwtPayloads();
        if (payloads == null) return null;
        return payloads.getStr("developerCode");
    }

    public static String getApplicationName() {
        String accessToken = getAccessToken();
        if (StrUtil.isBlank(accessToken)) return null;
        JWT jwt = JWT.of(accessToken);
        JSONObject payloads = jwt.getPayloads();
        if (payloads == null) return null;
        return payloads.getStr("application");
    }
}
